package com.zlz.open.ugs.exchange;

import com.zlz.open.ugs.chain.UgsChain;
import com.zlz.open.ugs.common.config.entity.runtime.UgsUrl;
import com.zlz.open.ugs.core.exchange.Exchange;
import com.zlz.open.ugs.core.module.Module;
import com.zlz.open.ugs.exchange.request.UgsRequest;
import com.zlz.open.ugs.exchange.response.UgsResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Author: zhulinzhong
 * @Date: 2024/5/30
 */
public class UgsExchange implements Exchange {

    private final ServerWebExchange webExchange;

    private final UgsRequest request;

    private final UgsResponse response;

    private final List<Module> modules;

    private UgsUrl url;

    public UgsExchange(ServerWebExchange delegate, UgsRequest request, UgsResponse response, List<Module> modules) {
        this.webExchange = delegate;
        this.request = request;
        this.response = response;
        this.modules = modules;
    }

    @Override
    public void setURLSource(UgsUrl ugsUrl) {
        this.url = ugsUrl;
    }

    @Override
    public String path() {
        return request.getRequest().getURI().getPath();
    }

    @Override
    public ServerWebExchange webExchange() {
        return this.webExchange;
    }

    @Override
    public UgsRequest request() {
        return this.request;
    }

    @Override
    public UgsResponse response() {
        return this.response;
    }

    @Override
    public Mono<Void> start() {
        // 包装执行链，使用worker处理请求与响应信息
        UgsChain ugsChain = new UgsChain.Wrapper(this, modules).wrapper(true);
        return ugsChain.work(this);
    }
}
